<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-31
 * Time: 09:29
 */

namespace app\common\model;


use app\common\exception\ParameterException;
use think\model\concern\SoftDelete;
use app\admin\validate\ShopCategory as Validate;

class ShopCategory extends BaseModel
{
    protected $hidden = ['update_time','delete_time'];

    // 使用软删除
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function product()
    {
        return $this->hasMany('ShopProduct','category_id','id');
    }

    /**
     * 获取图鸟商店商分类的分页数据
     * @param array $params
     * @return mixed
     */
    public static function getPaginationList(array $params)
    {
        static::validatePaginationData($params);

        $static = new static();

        $static = $static->order(['sort'=>'ASC']);

        foreach ($params as $name => $value) {
            $value = !is_array($value) ? trim($value) : $value;
            switch ($name) {
                case 'title':
                    if (!empty($value)) {
                        $like_text = '%' . $value . '%';
                        $static = $static->whereLike('title', $like_text);
                    }
                    break;
                case 'sort_order':
                    if (!empty($value)) {
                        $static = $static->order($params['sort_prop'], $value == 'descending' ? 'desc' : 'asc');
                    }
                    break;
            }
        }

        return $static
            ->paginate([
                'page' => $params['page'],
                'list_rows' => $params['limit']
            ], false);
    }

    /**
     * 添加商店分类数据
     * @param array $data
     * @return bool
     */
    public static function addCategory(array $data)
    {
        $validate = new Validate();
        if (!$validate->scene('add')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        $static = static::create($data);

        if (isset($static->id) && $static->id > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 编辑商店分类数据
     * @param array $data
     * @return bool
     */
    public static function editCategory(array $data)
    {
        $validate = new Validate();
        if (!$validate->scene('edit')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError(),
            ]);
        }

        $static = static::find($data['id']);

        $result = $static->allowField(['id','title','sort','status'])
            ->save($data);

        if ($result !== false) {
            return true;
        } else {
            return false;
        }
    }
}